package com.lovo.ssc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lovo.ssc.bean.AddressBean;
import com.lovo.ssc.mapper.AddressMapper;
import com.lovo.ssc.service.IAddressService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.transaction.Transaction;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

import static com.lovo.ssc.util.ExcelUtil.getCellValue;

/**
 * <p>
 * 用户的收货地址 服务实现类
 * </p>
 *
 * @author lovo
 * @since 2022-07-06
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, AddressBean> implements IAddressService {
    /**
     * 导出
     * 按用户编号导出收货地址excel
     * @param userId 用户编号
     * @param response 响应对象
     */
    @Override
    public void exportExcel(Integer userId, HttpServletResponse response) throws IOException {
        //1创建一个 workbook， 对应一个 excel文件
        // HSSFWorkbook -> xls
        // XSSFWorkbook -> xlsx
        HSSFWorkbook workbook = new HSSFWorkbook();
        //2在 workbook 里添加一个 sheet
        HSSFSheet sheet01 = workbook.createSheet("Sheet01");
        //3在 sheet01 里添加 表头第 0 行
        HSSFRow row = sheet01.createRow(0);
        //4创建单元格风格 进行设置
        HSSFCellStyle style = workbook.createCellStyle();
        //设置单元格居中
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        //设置表头 列名
        HSSFCell cell = row.createCell(0);
        cell.setCellStyle(style);
        cell.setCellValue("序号");

        cell = row.createCell(1);
        cell.setCellValue("收货人");
        cell = row.createCell(2);
        cell.setCellValue("地区");
        cell = row.createCell(3);
        cell.setCellValue("详细地址");
        cell = row.createCell(4);
        cell.setCellValue("收货人电话");
        cell = row.createCell(5);
        cell.setCellValue("是否为默认地址");

        //获取集合
        QueryWrapper qw = new QueryWrapper();
        qw.eq("userId", userId);
        List<AddressBean> list = baseMapper.selectList(qw);
        //遍历集合    创建单元格  并设置值
        for (int i = 0; i < list.size(); i++) {
            row = sheet01.createRow(i + 1);
            AddressBean one = list.get(i);
            row.createCell(0).setCellValue(one.getAddressId());
            row.createCell(1).setCellValue(one.getReceiver());
            row.createCell(2).setCellValue(one.getArea());
            row.createCell(3).setCellValue(one.getFullAddress());
            row.createCell(4).setCellValue(one.getTel());
            if (one.getDefaultAddress().equals("0")){
                row.createCell(5).setCellValue("否");
            }else {
                row.createCell(5).setCellValue("是");
            }
        }

        ServletOutputStream outputStream = response.getOutputStream();
        response.reset();
        long timeMillis = System.currentTimeMillis();
        String nowDate = new SimpleDateFormat("yyyy-MM-dd HH-MM-ss").format(new Date());
        response.setHeader("content-disposition","attachment;filename="+nowDate+timeMillis+".xls");
        response.setContentType("application/msexcel");
        workbook.write(outputStream);
        outputStream.close();
    }


    /**
     * 导入
     * 按用户编号导入收货地址excel
     * @param userId 用户编号
     * @param file excel文件对象
     * @return 是否导入成功
     */
    @Override
    @Transactional
    public String importExcel(Integer userId, MultipartFile file) throws Exception {
        Workbook workbook = null;
        String fileName = file.getOriginalFilename();
        if (fileName.endsWith(".xls")){
            workbook = new HSSFWorkbook(file.getInputStream());
        }else if (fileName.endsWith(".xlsx")){
            workbook = new XSSFWorkbook(file.getInputStream());
        }else {
            throw new Exception("该文件不是Excel文件");
        }

        Sheet sheet = workbook.getSheetAt(0);
        int lastRowNum = sheet.getLastRowNum();
        if (lastRowNum == 0){
            throw new Exception("文件内没有数据 请确认后重试！");
        }

        for (int i = 0; i < lastRowNum; i++) {
            Row row = sheet.getRow(i + 1);
            if (row != null){
                //创建一个对象
                AddressBean one = new AddressBean();
                //0读取Excel获取id 并给对象赋值
//                String id = getCellValue(row.getCell(0));
//                one.setId(id);
                //1读取Excel获取收货人并给对象赋值
                String receiver = getCellValue(row.getCell(1));
                one.setReceiver(receiver);
                //2读取Excel获取地区 并给对象赋值
                String area = getCellValue(row.getCell(2));
                if (!StringUtils.isEmpty(area)){
                    one.setArea(area);
                }
                //3读取Excel获取详细地址 并给对象赋值
                String fullAddress = getCellValue(row.getCell(3));
                if (!StringUtils.isEmpty(fullAddress)){
                    one.setFullAddress(fullAddress);
                }

                //4读取Excel获取收货人电话 并给对象赋值
                String tel = getCellValue(row.getCell(4));
                String regex = "^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$";

                if (Pattern.matches(regex,tel)){
                    if (!StringUtils.isEmpty(tel)){
                        one.setTel(tel);
                    }
                }else {
                    //当号码格式错误，回滚操作
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw new Exception("第"+(i+1)+"行号码格式错误！");
                }

                one.setUserId(userId);

                baseMapper.insert(one);
            }
        }
        return null;
    }


    /**
     * 按用户编号查询所有收货地址
     * @param userId 用户编号
     * @return 收货地址集合
     */
    @Override
    public List<AddressBean> findAllAddress(Integer userId) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("userId", userId);
        return baseMapper.selectList(qw);
    }

    /**
     * 通过地址编号查询收货地址
     * @param addressId 收货地址编号
     * @return 收货地址对象
     */
    @Override
    public AddressBean findAddressById(Integer addressId) {


        return baseMapper.selectById(addressId);
    }

}
